package com.shu.phao;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class Server {

	//public static final String HOST = "tcp://127.0.0.1:1883";
	public static final String HOST = "tcp://hbemq.mzjmedia.com:1883";

	public static final String TOPIC = "apk/update/35833612381111";
	
	private static final String clientid ="test_update"; 

	private MqttClient client;
	private MqttTopic topic;
	private String userName = "apk_client~!@#8$%^&*(3)_+";
	private String passWord = "check_pwswd~!@#tt$%^&*()_+";

	private MqttMessage message;

	public Server() throws MqttException {
		 //MemoryPersistence设置clientid的保存形式，默认为以内存保存
		client = new MqttClient(HOST, clientid, new MemoryPersistence());
		connect();
	}
	
	private void close() throws Exception {
		if(client != null) {
			client.disconnect();
			client.close(true);
		}
	}
	
	private void connect() {
		MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
               client.setCallback(new PushCallback());
               client.connect(options);
               topic = client.getTopic(TOPIC);
        } catch (Exception e) {
               e.printStackTrace();
        }
	}
	
	public void publish(MqttMessage message) throws MqttPersistenceException, MqttException{
		MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
        System.out.println(token.isComplete()+"========");
	}

	public static void main(String[] args) throws Exception {
		Server server =  new Server();
		server.message = new MqttMessage();
		server.message.setQos(1);
		server.message.setRetained(true);
		String playload = "{\"data\":{\"ram\":{\"total\":\"\",\"surplus\":\"\"},\"status\":\"\",\"serialPort\":{\"serial2\":\"\"},\"disk\":{\"total\":\"\",\"surplus\":\"\"},\"reqTime\":\"1516863428089\",\"cpu\":{\"temperature\":\"\",\"rate\":\"\"},\"machineId\":\"213243243\",\"longitude\":\"\",\"latitude\":\"\",\"net\":{\"sign\":\"\",\"type\":\"\",\"modal\":\"\"},\"version\":\"\"},\"version\":\"1\"}";
		server.message.setPayload(playload.getBytes());
        
		for(int i=0;i<1000;i++) {
			server.publish(server.message);
			//Thread.sleep(1000);
		}
        System.out.println(server.message.isRetained()+"------ratained状态");
        server.close();
	}


}
